package com.myrabbitmq;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class DirectConsumer {

    public static void main(String[] args) {
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("129.211.131.113");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/");
        //是否支持自动重连
        connectionFactory.setAutomaticRecoveryEnabled(true);
        connectionFactory.setNetworkRecoveryInterval(3000);
        try {
            Connection connection = connectionFactory.newConnection();

            Channel channel = connection.createChannel();

            //声明一个队列
            String queueName = "test_direct_queue";
            String exchangeName = "test_direct_exchange";
            String exchangeType = "direct";

            String routingKey = "test.direct";
            channel.exchangeDeclare(exchangeName,exchangeType,true,false,false,null);
            channel.queueDeclare(queueName,true,false,false,null);
            channel.queueBind(queueName,exchangeName,routingKey);


            //创建消费者
            boolean autoAck = false;
            channel.basicConsume(queueName, autoAck, "myConsumerTag",
                    new DefaultConsumer(channel) {
                        @Override
                        public void handleDelivery(String consumerTag,
                                                   Envelope envelope,
                                                   AMQP.BasicProperties properties,
                                                   byte[] body)
                                throws IOException
                        {
                            String routingKey = envelope.getRoutingKey();
                            String contentType = properties.getContentType();
                            long deliveryTag = envelope.getDeliveryTag();
                            // (process the message components here ...)
                            System.out.println(new String(body, "UTF-8"));
                            channel.basicAck(deliveryTag, false);
                        }
                    });
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
    }

}
